<template>
  <span
    class="get-code"
    :style="{ color: initColor }"
    :class="{ disabled: !timerData.again }"
    @click="OnCountStart"
    >{{ timerData.txt }}</span
  >
</template>
<script lang="ts" setup>
import { onMounted, reactive } from "vue"

interface PropType {
  auto?: boolean
  count?: number
  initTxt?: string
  countTxt?: string
  againTxt?: string
  initColor?: string
  interval?: number
}
const props = withDefaults(defineProps<PropType>(), {
  auto: false,
  count: 60,
  initColor: "#3D8EFF",
  initTxt: "获取验证码",
  countTxt: "秒后重发", // 60 秒重发  重新发送
  againTxt: "重新发送", // 60 秒重发  重新发送
  interval: 1000,
})
const emits = defineEmits(["countDown"])

const timerData = reactive({
  count: props.count,
  txt: props.initTxt,
  again: true,
  interval: props.interval,
})

const OnCountStart = () => {
  //   debugger
  if (!timerData.again) {
    return false
  } else {
    timerData.again = false
  }
  timerData.txt = timerData.count + props.countTxt
  !props.auto && emits("countDown")
  const timer = setInterval(() => {
    timerData.count--
    timerData.txt = timerData.count + props.countTxt
    if (timerData.count <= 0) {
      clearInterval(timer)
      timerData.count = props.count
      timerData.txt = props.againTxt
      timerData.again = true
      props.auto && emits("countDown")
    }
  }, timerData.interval)
}
onMounted(() => {
  props.auto && OnCountStart()
})
</script>
<style scoped lang="scss">
.get-code {
  cursor: pointer;
  &.disabled {
    color: #6c6c6c !important;
  }
}
</style>
